import request from '@/utils/request'

// 查询课程排课详细信息列表
export function listDetails(query) {
  return request({
    url: '/trainingManagement/details/list',
    method: 'get',
    params: query
  })
}

// 查询课程排课详细信息详细
export function getDetails(id) {
  return request({
    url: '/trainingManagement/details/' + id,
    method: 'get'
  })
}

// 新增课程排课详细信息
export function addDetails(data) {
  return request({
    url: '/trainingManagement/details',
    method: 'post',
    data: data
  })
}

// 修改课程排课详细信息
export function updateDetails(data) {
  return request({
    url: '/trainingManagement/details',
    method: 'put',
    data: data
  })
}

// 删除课程排课详细信息
export function delDetails(id) {
  return request({
    url: '/trainingManagement/details/' + id,
    method: 'delete'
  })
}

//提交排课要求年级学期
export function commitDetails(semesterId, academicYear, isScheduleCompleted = 0) {
  return request({
    url: '/trainingManagement/details/auto-scheduling',
    method: 'post',
    params: { semesterId, academicYear, isScheduleCompleted }
  });
}

/**
 * 分配教师到班级
 * @param {string} classId - 班级ID
 * @param {string} teacherId - 教师ID
 * @returns {Promise<AjaxResult>} - 包含操作结果的Promise
 */
export function assignTeacher(classId, teacherId) {
  return request({
    url: '/trainingManagement/details/assignTeacher',
    method: 'put',
    data: { classId, teacherId }
  });
}

// 添加的成绩录入

// 根据 courseScheduleDetailsId 查询学生列表
export function getEnrolledStudents(courseScheduleDetailsId) {
  return request({
    url: `/training/grade-input/students/${courseScheduleDetailsId}`,
    method: 'get'
  })
}

// 2. 提交单条成绩（供成绩录入页调用）
export function submitScore(data) {
  return request({
    url: '/training/grade-input/submit',
    method: 'post',
    data // 前端封装的成绩数据
  });
}
// 新增：获取成绩配置（与后端接口对应）
export function getScoreConfig(courseId) {
  return request({
    url: `/training/grade-input/config/${courseId}`, // 后端接口地址
    method: 'get'
  })
}
// 新增：保存成绩配置
export function saveScoreConfig(data) {
  return request({
    url: '/training/grade-input/config/save', // 对应后端 @PostMapping("/config/save")
    method: 'post',
    data
  })
}

/**
 * 根据课程ID、学期ID和年级查询课程排课信息及学生名单
 *
 * @param {string} courseId     课程ID
 * @param {number} semesterId   学期ID
 * @param {number} grade        年级
 * @return {Promise}            返回 Promise 对象
 */
export function selectStudentInfoListByTrainingProgramIds(trainingProgramIds) {
  // 关键：数组转字符串（如 ['id1','id2'] → "id1,id2"）
  const idsStr = Array.isArray(trainingProgramIds)
      ? trainingProgramIds.join(',')
      : trainingProgramIds; // 兼容单个ID的情况

  return request({
    url: '/student/studentManger/selectStudentInfoListByTrainingProgramIds',
    method: 'get',
    params: {
      trainingProgramIds: idsStr // 传递字符串，而非数组
    }
  });
}

/**
 * 通过教师ID获取对应的全部课程班及时间安排信息
 * @param {string} teacherId - 教师ID
 * @returns {Promise} - 包含课程班信息和时间安排的Promise对象
 */
export function getCourseScheduleDetailsByTeacherId(teacherId) {
  return request({
    url: '/trainingManagement/details/getCourseScheduleDetailsByTeacherId',
    method: 'get',
    params: {
      teacherId: teacherId
    }
  });
}


export const importScore = (formData) => {
  console.log('==== API层：调用importScore接口 ====');
  // 🔴 优化1：FormData直接打印显示为空，改为打印实际有效数据
  console.log('API层接收的参数：', {
    courseScheduleDetailsId: formData.get('courseScheduleDetailsId'), // 打印课程ID
    file: {
      name: formData.get('file')?.name, // 打印文件名
      size: formData.get('file') ? (formData.get('file').size / 1024 / 1024).toFixed(2) + 'MB' : '无文件', // 打印文件大小
      type: formData.get('file')?.type // 打印文件类型
    }
  });

  // 安全获取请求头（保留原有逻辑，无需改）
  const logHeaders = (event) => {
    if (event.target) {
      // 🔴 优化2：打印请求头时补充说明，明确当前格式
      console.log('实际发送的Content-Type：', event.target.getRequestHeader('Content-Type'));
    } else {
      console.log('上传事件target为undefined，跳过请求头打印');
    }
  };

  return request({
    url: '/training/grade-input/import',
    method: 'POST',
    data: formData,
    timeout: 30000,
    onUploadProgress: logHeaders,
    // 🔴 核心修改：明确指定请求头，与request.js拦截器配合，双重保障
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};